package com.linqi.freebie.ui.splash

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

@Composable
fun SplashScreen(
    onAnimationComplete: () -> Unit,
    word: String = "STEAM",
    logoText: String = "Freebie",
    letterDelay: Long = 300,
    letterSpacing: Dp = 0.dp,
    holdDuration: Long = 1000,
    logoFlyDuration: Int = 800,
    glowColor: Color = Color(0xFF00D8FF),
    baseColor: Color = Color(0xFF00B4D8),
    logoColor: Color = Color(0xFF33FF33),
    breathMinScale: Float = 0.98f,
    breathMaxScale: Float = 1.05f,
    breathDuration: Int = 800,
    glowRadiusMultiplier: Float = 0.6f,
    glowAlphaStart: Float = 0.7f,
    glowAlphaEnd: Float = 0.3f
) {
    val letterAlphas = remember { word.map { mutableStateOf(0f) } }
    val isBreathing = remember { mutableStateOf(true) }
    val breathScale = remember { Animatable(1f) }
    val logoOffsetX = remember { Animatable(300f) }
    val logoOffsetY = remember { Animatable(-300f) }
    val logoAlpha = remember { Animatable(0f) }
    val logoRotation = remember { Animatable(0f) }
    val logoScale = remember { Animatable(0.5f) }
    val showLogo = remember { mutableStateOf(false) }

    val rainbowColors = listOf(
        Color(0xFFFF0000), // 红
        Color(0xFFFF7F00), // 橙
        Color(0xFFFFFF00), // 黄
        Color(0xFF00FF00), // 绿
        Color(0xFF0000FF), // 蓝
        Color(0xFF4B0082), // 靛
        Color(0xFF8B00FF)  // 紫
    )

    data class Bubble(
        val center: Offset,
        val baseRadius: Float,
        val color: Color,
        val animScale: Animatable<Float, AnimationVector1D>,
        val offsetX: Animatable<Float, AnimationVector1D>,
        val offsetY: Animatable<Float, AnimationVector1D>,
        val maxOffset: Float,
        val durationMs: Int
    )

    var bubbles by remember { mutableStateOf<List<Bubble>>(emptyList()) }

    LaunchedEffect(Unit) {
        val random = Random(System.currentTimeMillis())
        bubbles = List(6) {
            val maxOffset = random.nextFloat() * 10f + 15f   // 位移幅度 15~25 px
            val durationMs = random.nextInt(1000, 2000)     // 1000~2000ms 往返周期
            Bubble(
                center = Offset(
                    x = random.nextFloat() * 800f + 100f,
                    y = random.nextFloat() * 600f + 100f
                ),
                baseRadius = random.nextFloat() * 40f + 20f,
                color = rainbowColors[random.nextInt(rainbowColors.size)].copy(alpha = 0.15f),
                animScale = Animatable(1f),
                offsetX = Animatable(0f),
                offsetY = Animatable(0f),
                maxOffset = maxOffset,
                durationMs = durationMs
            )
        }

        bubbles.forEachIndexed { index, bubble ->
            launch {
                // 呼吸放大缩小动画
                while (true) {
                    bubble.animScale.animateTo(
                        targetValue = 1.2f,
                        animationSpec = tween(durationMillis = 500, easing = FastOutSlowInEasing)
                    )
                    bubble.animScale.animateTo(
                        targetValue = 1f,
                        animationSpec = tween(durationMillis = 500, easing = FastOutSlowInEasing)
                    )
                }
            }
            launch {
                // X轴微小往返平移动画 ±maxOffset范围，周期 durationMs 毫秒
                while (true) {
                    bubble.offsetX.animateTo(bubble.maxOffset, tween(bubble.durationMs / 2, easing = LinearEasing))
                    bubble.offsetX.animateTo(-bubble.maxOffset, tween(bubble.durationMs, easing = LinearEasing))
                    bubble.offsetX.animateTo(0f, tween(bubble.durationMs / 2, easing = LinearEasing))
                }
            }

            delay(100L) // 错开启动，避免同步动画
        }
    }

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Canvas(modifier = Modifier.matchParentSize()) {
            bubbles.forEach { bubble ->
                val radius = bubble.baseRadius * bubble.animScale.value
                val offsetCenter = bubble.center + Offset(bubble.offsetX.value, bubble.offsetY.value)
                drawCircle(
                    color = bubble.color,
                    radius = radius,
                    center = offsetCenter
                )
            }
        }

        // STEAM 字母 - 光晕效果
        Row {
            word.forEachIndexed { index, letter ->
                if (index > 0) Spacer(modifier = Modifier.width(letterSpacing))

                Box(
                    modifier = Modifier
                        .graphicsLayer {
                            alpha = letterAlphas[index].value
                            scaleX = if (isBreathing.value) breathScale.value else 1f
                            scaleY = if (isBreathing.value) breathScale.value else 1f
                        }
                        .drawBehind {
                            if (letterAlphas[index].value > 0) {
                                val radius = size.width * glowRadiusMultiplier
                                drawCircle(
                                    brush = Brush.radialGradient(
                                        colors = listOf(
                                            glowColor.copy(alpha = glowAlphaStart),
                                            glowColor.copy(alpha = glowAlphaEnd),
                                            Color.Transparent
                                        ),
                                        center = Offset(size.width / 2, size.height / 2),
                                        radius = radius
                                    ),
                                    blendMode = BlendMode.Plus,
                                    radius = radius
                                )
                            }
                        }
                ) {
                    Text(
                        text = letter.toString(),
                        fontSize = 140.sp,
                        fontWeight = FontWeight.Bold,
                        fontFamily =  FontFamily.SansSerif,
                        color = baseColor,
                        modifier = Modifier.offset(0.dp, (-2).dp)
                    )
                }
            }
        }

        // Freebie Logo
        if (showLogo.value) {
            Text(
                fontSize = 70.sp,
                text = logoText,
                fontFamily =  FontFamily.Serif,
                fontWeight = FontWeight.Bold,
                color = logoColor,
                modifier = Modifier
                    .offset(logoOffsetX.value.dp, logoOffsetY.value.dp)
                    .rotate(45f + logoRotation.value)
                    .graphicsLayer {
                        alpha = logoAlpha.value
                        scaleX = logoScale.value
                        scaleY = logoScale.value
                    }
            )
        }
    }

    LaunchedEffect(Unit) {
        // 1. 逐个显示字母
        word.indices.forEach { index ->
            delay(letterDelay)
            letterAlphas[index].value = 1f
        }

        // 2. STEAM呼吸动画（放大缩小）
        repeat(3) {
            breathScale.animateTo(
                targetValue = breathMaxScale,
                animationSpec = tween(breathDuration / 2, easing = FastOutSlowInEasing)
            )
            breathScale.animateTo(
                targetValue = breathMinScale,
                animationSpec = tween(breathDuration / 2, easing = FastOutSlowInEasing)
            )
        }

        // 3. 停止呼吸动画（保持STEAM显示和光晕）
        isBreathing.value = false

        // 4. 显示Logo
        showLogo.value = true

        // Logo飞入动画
        launch { logoAlpha.animateTo(1f, tween(logoFlyDuration / 2)) }
        launch { logoOffsetX.animateTo(40f, tween(logoFlyDuration)) }
        launch { logoOffsetY.animateTo(20f, tween(logoFlyDuration)) }
        launch { logoRotation.animateTo(5f, tween(logoFlyDuration)) }
        launch { logoScale.animateTo(0.8f, tween(logoFlyDuration)) }

        // 5. 保持显示后回调
        delay(holdDuration)
        onAnimationComplete()
    }
}
